package com.anjiplus.template.gaea.business.modules.quartz.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import cn.hutool.db.ds.simple.SimpleDataSource;
import lombok.extern.slf4j.Slf4j;
import com.anjiplus.template.gaea.business.modules.quartz.util.Result;;
import org.example.quartz.service.UtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(path = "/TaskController")
public class TaskController {


    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value(value = "${spring.datasource.databaseType}")
    private String databaseType;
    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @Autowired
    private UtilService utilService;

    /**
     * 添加
     *
     * @param param
     * @return
     */
    @PostMapping("/queryYYVersion")
    public Result queryYYVersion(@RequestBody Map<String, Object> param) {
        try {
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from yy_version");
            return Result.success(mapList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }

    }

    /**
     * 添加
     *
     * @param param
     * @return
     */
    @PostMapping("/addTask")
    public Result addTask(@RequestBody Map<String, Object> param) {
        DataSource ds = new SimpleDataSource(jdbcUrl, username, password);
        try (Session session = Session.create(ds)) {
            if ("oracle".equals(databaseType)) {
                Entity entity = Entity.create("task_info");
                entity.set("ID", String.valueOf(IdUtil.getSnowflakeNextId()).substring(11));
                entity.set("delete_state", 0);
                for (Map.Entry<String, Object> stringObjectEntry : param.entrySet()) {
                    entity.set(stringObjectEntry.getKey(), stringObjectEntry.getValue());
                }
                session.insert(entity);
            } else {
                String insertSql = "INSERT INTO task_info (yyversion, task_class, task_desc )\n" +
                        "VALUES\n" +
                        "\t( " +
                        "'" + param.get("yyversion") + "', " +
                        "'" + param.get("task_class") + "', " +
                        "'" + param.get("task_desc") + "')";
                jdbcTemplate.update(insertSql);
            }
            return Result.success("新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 修改
     *
     * @param param
     * @return
     */
    @PostMapping("/updateTask")
    public Result updateTask(@RequestBody Map<String, Object> param) {
        DataSource ds = new SimpleDataSource(jdbcUrl, username, password);
        try (Session session = Session.create(ds)) {
            if ("oracle".equals(databaseType)) {
                String updateSql = "UPDATE \"task_info\" \n" +
                        "SET \"yyversion\" = '" + param.get("yyversion") + "',\n" +
                        "\"task_class\" = '" + param.get("task_class") + "',\n" +
                        "\"task_desc\" = '" + param.get("task_desc") + "'\n" +
                        "WHERE\n" +
                        "\t\"id\" = '" + param.get("id") + "';";
                jdbcTemplate.update(updateSql);

                /*Entity entity = Entity.create("task_info");
                for (Map.Entry<String, Object> stringObjectEntry : param.entrySet()) {
                    entity.set(stringObjectEntry.getKey(), stringObjectEntry.getValue());
                }
                session.update(entity, Entity.create("task_info").set("id", param.get("id")));*/
            } else {
                String updateSql = "UPDATE task_info \n" +
                        "SET yyversion = '" + param.get("yyversion") + "',\n" +
                        "task_class = '" + param.get("task_class") + "',\n" +
                        "task_desc = '" + param.get("task_desc") + "'\n" +
                        "WHERE\n" +
                        "\tid = '" + param.get("id") + "';";
                jdbcTemplate.update(updateSql);
            }

            return Result.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 修改
     *
     * @param id
     * @return
     */
    @PostMapping("/deleteTask")
    public Result deleteTask(@RequestParam("id") String id) {
        DataSource ds = new SimpleDataSource(jdbcUrl, username, password);
        try (Session session = Session.create(ds)) {
            if ("oracle".equals(databaseType)) {
                //查询taskInfo
                Map<String, Object> map = jdbcTemplate.queryForMap("select * from " + utilService.getGSYY() + ".\"task_info\" where \"id\" = '" + id + "'");
                String updateSql = "UPDATE \"task_info\" \n" +
                        "SET  \"delete_state\" = '1'\n" +
                        "WHERE\n" +
                        "\t\"id\" = '" + id + "'";
                jdbcTemplate.update(updateSql);
                //修改任务类
                jdbcTemplate.update("update " + utilService.getGSYY() + ".\"timed_reference_class\" set \"status\" = 0 where \"reference_path\" ='" + map.get("task_class") + "'");
            } else {
                //查询taskInfo
                Map<String, Object> map = jdbcTemplate.queryForMap("select * from " + utilService.getGSYY() + ".task_info where id = '" + id + "'");
                String updateSql = "UPDATE task_info \n" +
                        "SET  `delete_state` = '1'\n" +
                        "WHERE\n" +
                        "\t`id` = '" + id + "'";
                jdbcTemplate.update(updateSql);
                jdbcTemplate.update("update " + utilService.getGSYY() + ".timed_reference_class set status = 0 where reference_path ='" + map.get("task_class") + "'");
            }
            return Result.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 查询列表
     *
     * @param param
     * @return
     */
    @PostMapping("/getList")
    public Result getList(@RequestBody Map<String, Object> param) {
        try {
            String condition = "";
            // 拼接条件
//            if (!ObjectUtils.isEmpty(param.get("name"))) {
//                condition += " and ";
//            }else if(!ObjectUtils.isEmpty(param.get("name"))){
//                condition += " and ";
//            }
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from task_info where delete_state = 0 " + condition);
            return Result.success(mapList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 查询单条
     *
     * @param id
     * @return
     */
    @PostMapping("/getById")
    public Result getById(@RequestParam("id") Integer id) {
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap("select * from task_info where delete_state = 0 and id = ?", id);
            return Result.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }


}
